package cn.merryyou.generator.base;

import cn.merryyou.generator.dto.ResponseDto;
import cn.merryyou.generator.dto.ResponseUtil;
import cn.merryyou.generator.util.ServletUtils;
import cn.merryyou.generator.util.StringUtils;
import cn.merryyou.generator.vo.PageSupport;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
public class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

//    /**
//     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
//     */
//    @InitBinder
//    public void initBinder(WebDataBinder binder) {
//        // Date 类型转换
//        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
//            @Override
//            public void setAsText(String text) {
//                setValue(DateUtils.parseDate(text));
//            }
//        });
//    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageSupport.startPage();
    }

    /**
     * 获取request
     */
    public HttpServletRequest getRequest() {
        return ServletUtils.getRequest();
    }

    /**
     * 获取response
     */
    public HttpServletResponse getResponse() {
        return ServletUtils.getResponse();
    }

    /**
     * 获取session
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected <T> ResponseDto<List<T>> getDataTable(List<T> list) {
        return ResponseUtil.successLayuiData(list, new PageInfo(list).getTotal());
    }

    /**
     * 返回成功
     */
    public <T> ResponseDto<T> success(T data) {
        return ResponseUtil.success(0, data);
    }

    /**
     * 返回失败消息
     */
    public <T> ResponseDto<T> error() {
        return ResponseUtil.error(40000, "操作失败");
    }

    /**
     * 返回失败消息
     */
    public <T> ResponseDto<T> error(int code, String msg) {
        return ResponseUtil.error(code, msg);
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }
}
